package com.qf.blog.controller;

import com.alibaba.fastjson.JSON;
import com.qf.blog.dto.IndexDiscussPostDto;
import com.qf.blog.dto.MyPage;
import com.qf.blog.dto.TokenDto;
import com.qf.blog.entity.User;
import com.qf.blog.service.DiscussPostService;
import com.qf.blog.service.UserService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * User: key
 * ClassName:IndexController
 * Date: 2023/6/2
 * Time: 19:56
 * description:
 * //
 */
@Controller
public class IndexController {

    @Value("${blog.login.auto}")
    private boolean autuLogin;

    @Value("${blog.login.id}")
    private Integer userId;

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService postService;

    @Autowired
    private UploadManager uploadManager;


    @Value("${blog.qiniuyun.ak}")
    private String ak;

    @Value("${blog.qiniuyun.sk}")
    private String sk;

    @Value("${blog.qiniuyun.bucket}")
    private String bucket;

    @Value("${blog.qiniuyun.host}")
    private String host;


    /*
     * 文件上传
     * */
    @RequestMapping("/upload") // 上传必须是一个同步
    public String upload(MultipartFile file, Integer id) {

        // 1、文件名称
        String key = file.getOriginalFilename();

        // 2.认证
        Auth auth = Auth.create(ak, sk);

        // 3.获取token
        String upToken = auth.uploadToken(bucket, key);

        // 4.上传
        String path = null;
        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            path = host + defaultPutRet.key;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 写入数据库
        userService.updateUserHeader(id, host + "/" + key);

        return "redirect:/";
    }

//    @Value("${blog.host}")
//    private String hosts;
//
//    @Value("${server.port}")
//    private Integer port;

    // 用户只要访问/就会进入这个方法
    @GetMapping("/")
    public String index(HttpServletResponse response, Model model,
                        MyPage<IndexDiscussPostDto> page,
                        @RequestParam(defaultValue = "0") Integer orderMode) {
        // 1.判断用户是否已经登录了
        /*
         * 交付项目时记得注释掉这一行代码
         * */
//        if (loginUser == null) {
//            autoLogin(); // 实现自动登录
//        }
        // 2.查询帖子数据
        page = postService.indexDiscussPostData(page, orderMode);
        page.setPath("/");

//        String baseUrl = "http://" + hosts + ":" + port;
//        String baseUrl = "http://zuygva.natappfree.cc";
        // 3.把查询的出来的数据保存在Model中
        model.addAttribute("page", page);
//        model.addAttribute("baseUrl",baseUrl);
        return "index";
    }


    /*
     * 模糊查询
     * 模糊查询和帖子排序还未合并
     * */
    @RequestMapping("/search")
    public String search(Model model,
                         MyPage<IndexDiscussPostDto> page,
                         @RequestParam(defaultValue = "0") Integer orderMode,
                         String keyword) {
        if (ObjectUtils.isEmpty(keyword)) {
            return "redirect:/";
        }
        page = postService.indexDiscussPostData(page, orderMode, keyword);
        page.setPath("/search?keyword=" + keyword);
        model.addAttribute("page", page);
        return "index";
    }

    /*
     * 帖子排序
     * */
    @RequestMapping("/indexs")
    public String index(Model model,
                        MyPage<IndexDiscussPostDto> page,
                        Integer orderMode) {
        page = postService.indexDiscussPostData(page, orderMode);
        page.setPath("/indexs?orderMode=" + orderMode);
        model.addAttribute("page", page);
        return "index";
    }

    @GetMapping("/{page}.html")
    public String toPage1(@PathVariable String page) {
        System.out.println("page = " + page);
        return page;
    }

    @GetMapping("/{path}/{page}.html")
    public String toPage2(@PathVariable String path, @PathVariable String page) {
        System.out.println("path = " + path + ", page = " + page);
        return path + "/" + page;
    }

    /*
     * 为防止重复登陆，暂时固定一个账户
     * */
    public void autoLogin() {
        if (autuLogin) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpSession session = requestAttributes.getRequest().getSession();
            // 自动登录
            User user = userService.getById(userId);
            session.setAttribute("loginUser", user);
        }
    }
}